<?php


namespace app\common\service;


use app\admin\model\cart\Cart;
use app\admin\model\store\GoodsSku;
use think\facade\Cache;

class CartService extends BaseService
{
    /**
     * 加入购物车接口
     * @param $params
     */
    public static function create($params)
    {
        $uid = $params['uid'];
        $skuId = $params['sku_id'];
        $cartNum = $params['cart_num'];
        $sku = GoodsSku::find($skuId);
        $sku && $sku = $sku->toArray();
        if ($sku['sku_stock'] < $cartNum) {
            return self::fail('加入购物车失败，库存不足');
        }
        $data = Cart::where(['uid' => $uid, 'sku_id' => $skuId])->find();
        if ($data) {
            $data = $data->toArray();
            $cartId = $data['id'];
            $goodIdsMysql = Cart::where('uid', $uid)->column('sku_id');
            if (in_array($skuId, $goodIdsMysql)) {
                $flag = Cart::where('id', $cartId)->inc('cart_num', $cartNum)->update();
            } else {
                $flag = Cart::create($params);
            }
        } else {
            $flag = Cart::create($params);
        }
        if ($flag) {
            self::dbToRedis($uid);
            return self::success('添加购物车成功');
        } else {
            return self::fail('添加购物车失败，请重试');
        }
    }

    /**
     * Author:YangXinPeng
     * 购物车同步到redis
     * @param $uid
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function dbToRedis($uid)
    {
        $redis = Cache::store('redis');
        $redis->select(4);
        $redisKey = config('setting.cart') . $uid;
        $data = Cart::where('uid', $uid)->select();
        $data && $data = $data->toArray();
        foreach ($data as $key => $value) {
            $sku = GoodsSku::with('good')->find($value['sku_id']);
            $sku && $sku = $sku->toArray();
            $data[$key]['sku'] = $sku;
            $json = json_encode($data[$key]);
            $redis->hset($redisKey, $value['sku_id'], $json);
        }
    }

    /**
     * Author:YangXinPeng
     * 购物车前端接口
     * @param $uid
     * @return array
     */
    public static function getCarts($uid)
    {
        $key = config('setting.cart') . $uid;
        $redis = Cache::store('redis');
        $redis->select(4);
        $arr = [];
        if ($redis->exists($key)) {
            $data = $redis->hgetAll($key);
            foreach ($data as $value) {
                $goods = json_decode($value, true);
                $skus = json_decode($goods['sku']['attr_values'], true);
                $str = implode(",", $skus);
                $goods['sku']['attr_values'] = $str;
                $arr[] = $goods;
            }
            return self::success('成功', $arr);
        } else {
            $carts = Cart::where('uid', $uid)->select();
            $carts && $carts = $carts->toArray();
            foreach ($carts as $key => $value) {
                $sku = GoodsSku::with('good')->find($value['sku_id']);
                $sku && $sku = $sku->toArray();
                $carts[$key]['sku'] = $sku;
            }
            return self::success('成功', $carts);
        }
    }

    /**
     * Author:YangXinPeng
     * 购物车页面数量减少
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function reduceGoods($params)
    {
        if (!is_numeric($params['uid']) || !is_numeric($params['sku_id'])) {
            return self::fail('参数错误');
        }
        if ($params['uid'] <= 0 || $params['sku_id'] <= 0 ) {
            return self::fail('参数错误');
        }
        $redis = Cache::store('redis');
        $redis->select(4);
        $uid = $params['uid'];
        $skuId = $params['sku_id'];
        $where = [];
        $where['uid'] = $uid;
        $where['sku_id'] = $skuId;
        $key = config('setting.cart') . $uid;
        $flag = Cart::where($where)->dec('cart_num')->update();
        if ($flag) {
            $val = Cart::where($where)->value('cart_num');
            if ($val == 0) {
                Cart::where($where)->delete();
                $redis->hdel($key, $skuId);
            }
            self::dbToRedis($uid);
            return self::success('成功');
        } else {
            return self::fail('失败');
        }
    }

    /**
     * Author:YangXinPeng
     * 购物车页面数量增加
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addGoods($params)
    {
        if (!is_numeric($params['uid']) || !is_numeric($params['sku_id'])) {
            return self::fail('参数错误');
        }
        if ($params['uid'] <= 0 || $params['sku_id'] <= 0) {
            return self::fail('参数错误');
        }
        $uid = $params['uid'];
        $skuId = $params['sku_id'];
        $where = [];
        $where['uid'] = $uid;
        $where['sku_id'] = $skuId;
        $flag = Cart::where($where)->inc('cart_num')->update();
        if ($flag) {
            $num = Cart::where($where)->value('cart_num');
            $stock = GoodsSku::where('id', $skuId)->value('sku_stock');
            if ($num > $stock) {
                return self::fail('库存不足');
            }
            self::dbToRedis($uid);
            return self::success('成功');
        } else {
            return self::fail('失败');
        }
    }


    /**
     * Author:YangXinPeng
     * 查找购物车中特定商品
     * @param $params
     * @return array
     */
    public static function findCart($params)
    {
        $skuIds = $params['skuIds'];
        $uid = $params['uid'];
        $idsArr = explode(",", $skuIds);
        $key = config('setting.cart') . $uid;
        $redis = Cache::store('redis');
        $redis->select(4);
        $arr = [];
        if ($redis->exists($key)) {
            foreach ($idsArr as $id) {
                $goods = json_decode($redis->hget($key, $id), true);
                $skus = json_decode($goods['sku']['attr_values'], true);
                $str = implode(",", $skus);
                $goods['sku']['attr_values'] = $str;
                $arr[] = $goods;
            }
        }
        return self::success('成功', $arr);
    }

    /**
     * Author:YangXinPeng
     * 删除购物车
     * @param $uid
     * @param $cartId
     */
    public static function delCart($uid,$cartId)
    {
        $redis = Cache::store('redis');
        $redis->select(4);
        $redisKey = config('setting.cart') . $uid;
        $sku_id = Cart::where('id',$cartId)->value('sku_id');
        Cart::where('id',$cartId)->delete();
        $redis->hdel($redisKey, $sku_id);
    }
}